package com.tk.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tk.util.*;
import com.tk.entity.*;

public class Reply extends HttpServlet {

	public Reply() {
		super();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		doPost(request,response);
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		System.out.println(request.getParameter("theme"));
		System.out.println(request.getParameter("title"));
		System.out.println(request.getParameter("content"));
		
		Hero hero = (Hero)request.getSession().getAttribute("hero");
		
		int theme = Integer.parseInt(request.getParameter("theme"));
		String title = request.getParameter("title");
		String content = request.getParameter("content");
		
		
		Connection conn = DBUtil.getConnection();
		PreparedStatement ps1 = null;
		PreparedStatement ps2 = null;
		
		String sql1 = "insert into post (title,pid,content,replyTime,lastReply,posterPos,posterName)" +
				" values (?,?,?,now(),now(),?,?)";
		String sql2 = "update post set lastReply=now() where id=?";
		
		
		try {
			ps1 = conn.prepareStatement(sql1);
			ps1.setString(1, title);
			ps1.setInt(2, theme);
			ps1.setString(3, content);
			ps1.setInt(4, hero.getPosnum());
			ps1.setString(5, hero.getHname());
			ps1.execute();
			
			ps2 = conn.prepareStatement(sql2);
			ps2.setInt(1, theme);
			ps2.execute();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			DBUtil.close(ps1);
			DBUtil.close(ps2);
			DBUtil.close(conn);
		}
		
		request.getRequestDispatcher("PaginationTheme").forward(request, response);
		
	}

}
